#include "MainScreenTouchLayer.h"

MainScreenTouchLayer::MainScreenTouchLayer()
	: m_pTouchListener(NULL)
{
}

MainScreenTouchLayer::~MainScreenTouchLayer()
{
}

bool MainScreenTouchLayer::init()
{
	if (cocos2d::Layer::init())
	{
		auto listener = cocos2d::EventListenerTouchAllAtOnce::create();
		listener->onTouchesBegan = CC_CALLBACK_2(MainScreenTouchLayer::onTouchesBegan, this);
		listener->onTouchesMoved = CC_CALLBACK_2(MainScreenTouchLayer::onTouchesMoved, this);
		listener->onTouchesEnded = CC_CALLBACK_2(MainScreenTouchLayer::onTouchesEnded, this);
		_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
		return true;
	}
	return false;
}

void MainScreenTouchLayer::onTouchesBegan(const std::vector<cocos2d::Touch*>& touches, cocos2d::Event  *event)
{
	std::vector<moveVec2> vecMoveVec2s;
	for (auto &touch : touches)
	{
		m_mapTouchLocations.insert(std::make_pair(touch->getID(), touch->getLocation()));
		vecMoveVec2s.push_back(moveVec2(touch->getID(), touch->getLocation(), cocos2d::Vec2(0, 0)));
	}

	if (m_pTouchListener)
	{
		m_pTouchListener->onTouchesBegan(vecMoveVec2s);
	}
}

void MainScreenTouchLayer::onTouchesMoved(const std::vector<cocos2d::Touch*>& touches, cocos2d::Event  *event)
{
	std::vector<moveVec2> vecMoveVec2s;
	for (auto &touch : touches)
	{
		for (auto &startPos : m_mapTouchLocations)
		{
			if (startPos.first == touch->getID())
			{
				vecMoveVec2s.push_back(moveVec2(startPos.first, startPos.second, touch->getLocation() - startPos.second));
			}
		}
	}

	if (m_pTouchListener)
	{
		m_pTouchListener->onTouchesMoved(vecMoveVec2s);
	}
}

void MainScreenTouchLayer::onTouchesEnded(const std::vector<cocos2d::Touch*>& touches, cocos2d::Event  *event)
{
	std::vector<moveVec2> vecMoveVec2s;
	for (auto &touch : touches)
	{
		m_mapTouchLocations.erase(touch->getID());
		vecMoveVec2s.push_back(moveVec2(touch->getID(), touch->getLocation(), cocos2d::Vec2(0, 0)));
	}

	if (m_pTouchListener)
	{
		m_pTouchListener->onTouchesEnded(vecMoveVec2s);
	}
}

void MainScreenTouchLayer::onTouchesCancelled(const std::vector<cocos2d::Touch*>& touches, cocos2d::Event  *event)
{
	onTouchesEnded(touches, event);
}

void MainScreenTouchLayer::setTouchListener(MainScreenTouchListener *touchListener)
{
	m_pTouchListener = touchListener;
}